
package de.unihannover.se.restlab.microblog.data;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import de.unihannover.se.restlab.microblog.models.User;

/** A list of users.
 * @author restlab_c */
@Stateless
@XmlRootElement
@XmlType(namespace = "http://www.w3.org/2005/AtomUserStorage")
public class UserStorage extends AbstractStorage {

	public static UserStorage getStorage () {
		return (UserStorage)getConcreteStorage(UserStorage.class);
	}

	@PersistenceContext
	private EntityManager em;

	@XmlElement(name = "user")
	private List<User> users = new ArrayList<User>();

	public User createUser (String name) {
		int nextId = 1;
		if (!users.isEmpty()) {
			nextId = users.size() + 1;
		}
		User user = new User(nextId, name);
		users.add(user);

		em.persist(user.getPersistence());

		return user;
	}

	public List<User> getUsers () {
		return users;
	}

	public User getUser (Integer id) {
		return (id < users.size() + 1) ? users.get(id - 1) : null;
	}

	public void removeUser (User user) {
		// em.remove(user);
		// em.getTransaction().commit();
		// em.close();
		users.remove(user.getPersistence());
	}

	public void clear () {
		setup();
		for(User u : users) {
			em.remove(u.getPersistence());
		}
		users.clear();
	}

	public void setup () {
		int i=1;
		while(true) {
			
			//em.createQuery("select u from User u");
			de.unihannover.se.restlab.microblog.jpamodels.User u = em.find(de.unihannover.se.restlab.microblog.jpamodels.User.class, i++);
			if(u == null) break;
			users.add(new User(u));
		}
	}

}
